package com.nd.OSS;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @program: project2mall
 * @description: 对象存储工具类
 * @author: shit_code_builder
 * @create: 2021-06-06 09:43
 **/
@Component
//@Configuration
//@EnableConfigurationProperties(AliyunProperties.class)
public class OSSBootUtil {

    @Autowired
    AliyunProperties properties;

//    public OSSBootUtil(AliyunProperties properties) {
//        this.properties = properties;
//    }
    private OSSBootUtil(){}


    /**
     * oss 工具客户端
     */
////    @Value("${AccessKeyID}")
//    private static String AccessKeyID = "LTAI5tSCp3PN7Tt72AHQoQk4";
////    @Value("${OSS.AccessKeySecret}")
//    private static String AccessKeySecret="WODHBwxGEed0R3wOsUso7qsPicXD3j";
////    @Value("${OSS.Endpoint}")
//    private static String Endpoint="oss-cn-chengdu.aliyuncs.com";
////    @Value("${OSS.SUFFER_URL}")
//    private static String SUFFER_URL ="project2mall-oss.oss-cn-chengdu.aliyuncs.com";
////    @Value("${OSS.BUCKETNAME}")
//    private static String BUCKETNAME="project2mall-oss";
//
////    @Autowired


    private volatile OSSClient ossClient = null;

    public  String getBUCKETNAME(){
        return properties.getBucket();
    }
    public  String getSufferUrl(){
        return properties.getSufferUrl();
    }

    public OSSClient getOSSClient(String token) throws Exception {

        ClientConfiguration clientConfiguration = new ClientConfiguration();
        clientConfiguration.setMaxConnections(10);
        clientConfiguration.setConnectionTimeout(-1);
        // 设置最大的重试次数为3
        clientConfiguration.setMaxErrorRetry(3);
        // 设置Socket传输数据超时的时间为2000毫秒
        clientConfiguration.setSocketTimeout(2000);
        DefaultCredentialProvider defaultCredentialProvider;
        if ("".equals(token)) {
            defaultCredentialProvider = new CredentialsProviderFactory().newDefaultCredentialProvider(properties.getAccessKeyId(),properties.getAccessKeySecret(),"res.data.securityToken");
        }else {
          defaultCredentialProvider = new CredentialsProviderFactory().newDefaultCredentialProvider(properties.getAccessKeyId(),properties.getAccessKeySecret(), "res.data.securityToken");
        }
//         ossClient = new OSSClient(properties.getEndpoint(),defaultCredentialProvider,clientConfiguration);
        ossClient = new OSSClient(properties.getEndpoint(),properties.getAccessKeyId(),properties.getAccessKeySecret());
        if (ossClient.doesBucketExist(getBUCKETNAME())){
            System.out.println("bucket已经存在,可以使用");

        }else {
            CreateBucketRequest bucketRequest = new CreateBucketRequest(null);
            bucketRequest.setBucketName(properties.getBucket());
            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(bucketRequest);
            System.out.println("bucket创建成功");
        }
        return ossClient;
    }

    public void closeOSSClient() throws Exception {
        if (ossClient!=null) {
            ossClient.shutdown();
        }

    }


//    public static String uploadFiles(MultipartFile myFile, String token) throws Exception {
//        OSSClient ossClient = getOSSClient(token);
//
//        String fileType = myFile.getOriginalFilename().substring(myFile.getOriginalFilename().lastIndexOf(".")+1);
//
//        String updateTime = DateTime.now().toDateStr();
//        String uuid = UUID.randomUUID().toString();
//
//        String filename = fileType+"/"+updateTime+"/"+uuid+"-"+myFile.getOriginalFilename();
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(myFile.getBytes());
//        try {
//            ossClient.putObject(BUCKETNAME,filename,byteArrayInputStream);
//        } catch (OSSException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//
//        }finally {
//            OSSBootUtil.closeOSSClient();
//        }
//        String url = SUFFER_URL+"/"+filename;
//
//        System.out.println(url);
//        return url;
//    }
}
